<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表 -->
    <el-card class="box-card">
      <el-button type="primary" @click="addRolesFlag = true">添加角色</el-button>
       <el-table
        :data="RolesList"
        border
        stripe
        style="width: 100%">
        <el-table-column type="expand" label="">
          <template slot-scope="scope">
            <!-- 栅格  第一行 -->
          <el-row v-for="(item, index) in scope.row.children" :key="item.id" class="border-bottom" :class="index===0 ? 'border-top': ''">
            <!-- 第一列 一级标题 -->
            <el-col :span="8">
              <el-tag>{{item.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 第二列 二级标题 -->
            <el-col :span="15">
              <!-- 第二列 第一行 -->
              <el-row :class="index===0 ? '': 'border-top'"  v-for="(item2,index) in item.children" :key="item2.id">
                <!-- 第二列 第一行 第一列 -->
                <el-col :span="9">
                 <el-tag type="success">{{item2.authName}}</el-tag>
                 <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 第二列 第二行 -->
                <el-col :span="15" >
                  <el-tag closable @close="removeTag(scope.row,item3.id)" type="warning" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" >
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column  label="角色操作" width="300px">
           <template slot-scope="scope">
             <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
             <el-button type="danger"  icon="el-icon-delete" size="mini" @click="delRoles(scope.row.id)">删除</el-button>
             <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesFlag"
      width="50%"
      >
      <el-form ref="addRolesForm" :model="addRolesForm" label-width="80px" :rules="addRolesFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesFlag = false">取 消</el-button>
        <el-button type="primary" @click="addRolesEvent">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配对话框 -->
    <el-dialog
      title="提示"
      @close="removedefaultChecked"
      :visible.sync="allotRights"
      width="50%">
      <el-tree ref="tree" :data="rights" node-key="id" :default-checked-keys="defaultChecked" show-checkbox default-expand-all :props="treeDefaultProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRights = false">取 消</el-button>
        <el-button type="primary" @click="settingRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      RolesList: [],
      // 添加角色Flag
      addRolesFlag: false,
      // 添加角色对话框默认数据
      addRolesForm: {
        roleName: 'Yn',
        roleDesc: 'Desc'
      },
      // 添加角色 表单验证
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限flag
      allotRights: false,
      // 分配角色数据
      rights: [],
      // 配置树形结构的label属性
      treeDefaultProps: {
        label: 'authName'
      },
      // 配置默认选中  注意:配置此选项需要给标签设置 node-key="id"
      defaultChecked: [],
      // 分配权限时 需要的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$axios.get('roles')
      this.RolesList = res.data
    },
    // 移除tag
    removeTag (roles, rightsId) {
      this.$messageBox.confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${roles.id}/rights/${rightsId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        // 直接调用getRolesList会刷新页面  需要再删除后 后端返回row.children的数据且赋值即可
        roles.children = res.data
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('取消删除')
      })
    },
    // 创建角色功能
    addRolesEvent () {
      this.$refs.addRolesForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) return this.$message.console.error('创建角色失败')
        this.getRolesList()
        this.addRolesFlag = false
        this.$message.success('创建角色成功')
      })
    },
    // 删除角色功能
    delRoles (id) {
      this.$messageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRolesList()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('取消删除')
      })
    },
    // 分配权限功能
    async setRights (row) {
      this.allotRights = true
      // 获取树形权限列表
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.rights = res.data
      // 获取ID切存储在data中
      console.log(row)
      this.roleId = row.id
      this.getRigths(row)
    },
    // 定义递归函数循环出 需要选中的id
    getRigths (row) {
      if (!row.children) return this.defaultChecked.push(row.id)
      row.children.forEach(item => {
        this.getRigths(item)
      })
    },
    // 每次关闭对话框  清空选中 也就是清空数组 defaultChecked
    removedefaultChecked () {
      this.defaultChecked = []
    },
    // 点击确定设置角色权限
    async settingRights () {
      // 绑定了nodekey= id 即可通过自身方法拿到所有id
      const checkedkeys = this.$refs.tree.getCheckedKeys()
      const HalfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      const rids = [...checkedkeys, ...HalfCheckedKeys].join(',')
      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids })
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message.success('分配成功')
      this.getRolesList()
      this.allotRights = false
    }
  }
}
</script>

<style scoped lang="less">
.el-tag{
  margin: 10px;
}
.border-top{
  border-top: 1px solid #eee;
}
.border-bottom{
  border-bottom: 1px solid #eee;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>
